package com.example.forumsystem.demos.web.service.impl;

import com.example.forumsystem.demos.web.common.ResultCode;
import com.example.forumsystem.demos.web.exception.ApplicationException;
import com.example.forumsystem.demos.web.mapper.UserInfoMapper;
import com.example.forumsystem.demos.web.model.Result;
import com.example.forumsystem.demos.web.model.UserInfo;
import com.example.forumsystem.demos.web.service.IUserService;
import com.example.forumsystem.demos.web.utils.MD5Util;
import com.example.forumsystem.demos.web.utils.StringUtil;
import com.example.forumsystem.demos.web.utils.UUIDUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServlet;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo selectByUserName(String username) {
        if (StringUtil.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userInfoMapper.selectByName(username);
    }

    @Override
    public void createNormalUser(UserInfo user) {
        // 1. 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常， 统一抛出ApplicationException
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 2. 按用户名查询用户信息
        UserInfo existsUser = userInfoMapper.selectByName(user.getUsername());
        // 判断用户是否存在
        if (existsUser != null) {
            // 打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(Result.fail(ResultCode.FAILED_USER_EXISTS));
        }

        // 3. 新增用户流程,设备默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        // 写入数据库
        int row = userInfoMapper.insertSelective(user);
        if (row != 1) {
            // 打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            // 抛出异常
            throw new ApplicationException(Result.fail(ResultCode.FAILED_CREATE));
        }
        // 打印日志
        log.info("新用户成功. username = " + user.getUsername() + ". ");
    }

    @Override
    public UserInfo login(String username, String password) {
        UserInfo user = userInfoMapper.selectByName(username);
        if (user == null){
            log.info("输入的用户: " + username + ", 不存在");
            throw  new ApplicationException(Result.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        if (!user.getPassword().equals(MD5Util.md5Salt(password, user.getSalt()))){
            log.info("密码输入错误，输入的密码是：" + password);
            throw  new ApplicationException(Result.fail(ResultCode.FAILED_LOGIN));
        }

        log.info("登录成功, username = " + username);
        return user;
    }

    @Override
    public UserInfo selectById(Long id) {
        if (id == null){
            log.warn("未传入用户id");
            throw new ApplicationException(new Result("传入的用户id为null"));
        }

        //用户不为null，从数据库中查找
        UserInfo user = userInfoMapper.selectByPrimaryKey(id);
        if (user == null){
            log.warn("用户不存在");
            throw new ApplicationException(new Result("数据库中不存在该用户"));
        }

        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id < 0){
            log.warn("新增用户发帖数失败，传入的用户id为：" + id);
            throw new ApplicationException(Result.fail("新增用户发帖数失败"));
        }

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(id);

        if (userInfo == null){
            log.warn("未查询到当前用户，传入的id为：" + id);
            throw new ApplicationException(Result.fail("新增用户发帖数失败"));
        }

        UserInfo userTmp = new UserInfo();
        userTmp.setId(userInfo.getId());
        userTmp.setArticleCount(userInfo.getArticleCount() + 1);
        Integer res = userInfoMapper.updateByPrimaryKeySelective(userTmp);

        if (res != 1){
            log.warn("更新用户发帖数失败，联系管理员");
            throw new ApplicationException(Result.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void cutOneArticleCountById(Long userId) {
        if (userId == null || userId <= 0) {
            log.warn("参数校验失败，传入的用户id有误，为: " + userId);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        UserInfo user = userInfoMapper.selectByPrimaryKey(userId);
        if (user == null) {
            log.warn("用户不存在，用户id为：" + userId);
            throw new ApplicationException(Result.fail(ResultCode.ERROR_IS_NULL));
        }

        UserInfo updateUser = new UserInfo();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);

        //如果之前减1后，发帖数<0了，直接把发帖数改为0
        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }

        int row = userInfoMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn("更新用户发帖数失败");
            throw new ApplicationException(Result.fail(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyBasin(UserInfo user) {
        if (user == null || user.getId() == null || user.getId() < 0) {
            log.warn("用户id错误，为：" + user.getId());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        UserInfo existsUser = userInfoMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn("用户不存在");
            log.warn("用户不存在");
            throw new ApplicationException(Result.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }


        UserInfo updateUser = new UserInfo();
        updateUser.setId(user.getId());

        //校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
        }

        // 校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
        }

        //校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
        }
        //校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
        }

        int row = userInfoMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn("更新用户信息失败");
            throw new ApplicationException(Result.fail(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id == null || id < 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn("传来的参数有误, 用户id: " + id + ", 新密码: " + newPassword + ", 旧密码" + oldPassword);
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 校验用户是否存在
        UserInfo user = userInfoMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.warn("用户不存在, 或者是禁言状态");
            throw new ApplicationException(Result.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 加密老密码，判断输入的老密码是否正确
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn("输入的老密码并不正确，输入的老密码: " + oldPassword + ", 真正的密码" + user.getPassword());
            throw new ApplicationException(Result.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        String salt = UUIDUtil.UUID_32(); //生成一个新的盐值
        String newMD5Password = MD5Util.md5Salt(newPassword, salt);

        UserInfo updateUser = new UserInfo();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(newMD5Password);
        Date date = new Date();
        updateUser.setUpdateTime(date);

        int row = userInfoMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn("更新用户密码失败");
        }

    }
}
